package com.bookocean.infrastructure.schedule;

import com.bookocean.application.common.RedisConstants;
import com.bookocean.domain.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Set;

/**
 * 小说完结投票清理定时任务
 * 
 * @author BookOcean
 * @since 2024-01-01
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class NovelVoteCleanupTask {
    
    private final RedisUtils redisUtils;
    
    /**
     * 每小时检查一次过期的投票
     */
    @Scheduled(fixedRate = 3600000) // 1小时 = 3600000毫秒
    public void cleanupExpiredVotes() {
        log.info("开始清理过期的完结投票");
        
        try {
            // 查找所有投票key
            String pattern = RedisConstants.NOVEL_COMPLETE_VOTE_PREFIX + "*";
            Set<String> voteKeys = redisUtils.keys(pattern);
            
            int cleanedCount = 0;
            for (String voteKey : voteKeys) {
                try {
                    // 检查投票状态
                    String status = (String) redisUtils.hGet(voteKey, "status");
                    if (!"voting".equals(status)) {
                        continue; // 只处理投票中的状态
                    }
                    
                    // 检查过期时间
                    LocalDateTime expireTime = (LocalDateTime) redisUtils.hGet(voteKey, "expireTime");
                    if (expireTime != null && LocalDateTime.now().isAfter(expireTime)) {
                        // 投票过期，设置为过期状态
                        redisUtils.hSet(voteKey, "status", "expired");
                        redisUtils.hSet(voteKey, "result", "expired");
                        redisUtils.hSet(voteKey, "completedTime", LocalDateTime.now());
                        
                        cleanedCount++;
                        log.info("清理过期投票: {}", voteKey);
                    }
                } catch (Exception e) {
                    log.error("清理投票失败: {}, 错误: {}", voteKey, e.getMessage(), e);
                }
            }
            
            log.info("完结投票清理完成，清理数量: {}", cleanedCount);
            
        } catch (Exception e) {
            log.error("清理过期投票任务执行失败: {}", e.getMessage(), e);
        }
    }
}
